import { Component, OnInit } from '@angular/core';
import {environment} from "../../../../environments/environment";
import {EventBusService} from "../../../services/event-bus.service";
import {ActivatedRoute, Router} from "@angular/router";
import {PublicService} from "../../../services/public.service";
import {StorageService} from "../../../services/storage.service";
import {Message, TreeNode} from "primeng/primeng";
import {InventorymaintenanceService} from "../../inventorymaintenance.service";
import {PUblicMethod} from "../../public/PUblicMethod";

@Component({
  selector: 'app-malfunction-turn-inventory',
  templateUrl: './malfunction-turn-inventory.component.html',
  styleUrls: ['./malfunction-turn-inventory.component.scss']
})
export class MalfunctionTurnInventoryComponent implements OnInit {

  resObj: Object;
  sid: string;
  initStatus = '';                       // 故障单状态

  malDepPersonOptions: any = [];         // 分配个人可选数据
  malDepPerson = '';                     // 分配个人
  malReasonOptions: any = [];            // 升级原因可选数据
  malReason = '';                        // 升级原因

  malUpTime = '';                        // 升级时间


  malStatus = '新建';                    // 状态
  reporter: TreeNode[] = [];             // 报告人
  zh: any;
  dealTime: Date;                        // 受理时间
  uploadedFiles = [];
  uploadRes = [];                        // 上传成功返回的文件路径对象
  ip: string;                            // 127.0.0.1:80
  message: Message[] = [];               // 交互提示弹出框
  msg: Message[] = [];                   // 验证弹出框

  selectedDepartment: TreeNode[] = [];   // 分配至部门
  departementDisplay: boolean;           // 树显示控制
  filesTree4: TreeNode[];                // 树的可选值
  selected: TreeNode[];                  // 树的选中值
  dialogHeader: string;                  // 组织树弹框标题
  currentTreeName: string;               // 当前要加载的树
  selectedMode: string;                  // 树的选择模式

  malReviceTime = '';                    // 接收时间
  oldselectedDepartment = {};
  oldMalDepPerson: any;
  distributeTime = '';


  constructor(private maintenanceService: InventorymaintenanceService,
              private router: Router,
              private storageService: StorageService,
              private publicService: PublicService,
              private activatedRouter: ActivatedRoute,
              private eventBusService: EventBusService) { }

  ngOnInit() {
    this.sid = this.activatedRouter.snapshot.paramMap.get('id');
    this.initTrick(this.sid);
    this.initStatus = this.activatedRouter.snapshot.paramMap.get('status');
    this.zh = new PUblicMethod().initZh();
    this.dealTime = new Date();
    this.getDepPerson();
    this.departementDisplay = false;
    this.ip = environment.url.management;
    this.malReasonOptions = [
      {name: '分派错误', code: 'fpcw'},
      {name: '工作交接', code: 'gzjj'}
    ];
    this.maintenanceService.getFlowChart(  this.initStatus).subscribe(res => {
      this.eventBusService.maintenance.next(res);
    });
  }
  initTrick(s) {
    this.maintenanceService.getTrick(s).subscribe(res => {
      let data = res['data'];
      if (res['errcode'] === '00000') {
        this.resObj = data;
        this.oldselectedDepartment = data['acceptor_org'];
        this.oldMalDepPerson = data['acceptor'];
        this.distributeTime = data['assign_time'];
        this.malReviceTime = data['accept_time'];
      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `获取故障单信息失败${res}`});
      }
    });
  }
  onBeforeUpload(event) {
    let token = this.storageService.getToken('token');
    event.formData.append('access_token', token);
  }
  onUpload(event) {
    let xhrRespose = JSON.parse(event.xhr.response);
    if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
      this.uploadRes = xhrRespose['datas'];
      this.message = [];
      this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
    }else {
      this.message = [];
      this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
    }
  }
  // 部门组织树模态框
  showTreeDialog(which: string) {
    this.currentTreeName = which;
    this.selected = [];
    this.filesTree4 = [];
    this.departementDisplay = true;
    switch (which) {
      case 'selectedDepartment':
        this.dialogHeader = '请选择部门';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
    }
  }
  // 组织树懒加载
  nodeExpand(event) {
    switch ( this.currentTreeName ) {
      case 'selectedDepartment':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
    }
  }
  nodeSelect(event) {
    console.log(event);
  }
  // 清空组织树选中内容
  clearTreeDialog (which) {
    switch ( which ) {
      case 'selectedDepartment':
        this.selectedDepartment = [];
        this.getDepPerson();
        break;
    }
  }
  // 组织树最后选择
  closeTreeDialog() {
    switch ( this.currentTreeName ) {
      case 'selectedDepartment':
        this.selectedDepartment = this.selected;
        this.getDepPerson(this.selected['oid']);
        break;
    }
    this.departementDisplay = false;
  }
  getDepPerson(oid?) {
    this.publicService.getApprovers(oid).subscribe(res => {
      if (!res) {
        this.malDepPersonOptions = [];
      }else {
        this.malDepPersonOptions = res;
      }
    });
  }

  //  处理故障单
  deal() {
    this.router.navigate(['/index/maintenance/malfunctionBase/malfunctionSolved', {id: this.sid, status: this.malStatus}]);
  }

  submitTrick() {
    let paper = {
      'sid': this.sid,
      'processor':  this.malDepPerson['name'],
      'processor_pid':  this.malDepPerson['pid'],
      'processor_org':  this.selectedDepartment['label'],
      'processor_org_oid':  this.selectedDepartment['oid'],
      'reassign_reason': this.malReason['name']
    };
    console.log(paper);
    if (!paper.sid
      || !paper.processor
      || !paper.processor_org
      || !paper.reassign_reason
    ) {
      this.showError();
    }else {
      this.turnPost(paper);
    }
  }
  showError() {
    this.msg = [];
    this.msg.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
  }
  turnPost(paper) {
    this.maintenanceService.turnTrick( paper ).subscribe(res => {
      if ( res === '00000' ) {
        this.message = [];
        this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
        window.setTimeout(() => {
          this.router.navigateByUrl('/index/maintenance/malfunctionBase');
        }, 1100);
      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
      }
    });
  }


}
